//
//  WBTextDiyView.m
//  WeiBo
//
//  Created by EDZ on 2017/9/30.
//  Copyright © 2017年 powertorque. All rights reserved.
//

#import "WBTextDiyView.h"

#import "WBStatus.h"

@interface WBTextDiyView ()

@property (nonatomic, strong) NSArray<WBVisialLink *> *links;

@end

@implementation WBTextDiyView 

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        UITextView *textView = [[UITextView alloc] init];
        textView.backgroundColor = [UIColor clearColor];
        [self addSubview:textView];
        _textView = textView;
        
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.textView.frame = self.bounds;
}

#pragma mark - Getter

- (NSArray<WBVisialLink *> *)links
{
    if (!_links) {
        NSMutableArray<WBVisialLink *> *links = [NSMutableArray arrayWithCapacity:0];
        [self.status.linkResults enumerateObjectsUsingBlock:^(WBLinkResult * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            WBVisialLink *link = [[WBVisialLink alloc] init];
            link.linkResult = obj;
            
            self.textView.selectedRange = obj.range;
            NSArray *selectionRects = [self.textView selectionRectsForRange:self.textView.selectedTextRange];
            NSMutableArray<NSValue *> *rects = [NSMutableArray arrayWithCapacity:0];
            for (UITextSelectionRect *selectionRect in selectionRects) {
                CGRect rect = selectionRect.rect;
                if (rect.size.width == 0 || rect.size.height == 0) continue;
                [rects addObject:[NSValue valueWithCGRect:rect]];
            }
            link.rects = rects;
            [links addObject:link];
        }];
        _links = links;
    }
    return _links;
}

#pragma mark - Setter

- (void)setStatus:(WBStatus *)status
{
    _status = status;
    
    self.textView.attributedText = status.attributeText;
    self.links = nil;
    [self removeCover];
}

#pragma mark - Touch

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    // 移除所有的选中效果（更严谨）
    [self removeCover];
    
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self.textView];
    
    // 遍历，判断点是不是在链接上
    __block WBVisialLink *link = nil;
    [self.links enumerateObjectsUsingBlock:^(WBVisialLink * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (link) *stop = YES;
        [obj.rects enumerateObjectsUsingBlock:^(NSValue * _Nonnull value, NSUInteger idx, BOOL * _Nonnull stop) {
            if (CGRectContainsPoint(value.CGRectValue, point)) {
                link = obj;
                *stop = YES;
            }
        }];
    }];
    
    if (link) { // 点击了链接范围
        [link.rects enumerateObjectsUsingBlock:^(NSValue * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            WBRectView *cover = [[WBRectView alloc] initWithFrame:obj.CGRectValue];
            cover.userInteractionEnabled = NO;
            cover.link = link;
            cover.backgroundColor = kCSSColorRGB(194, 205, 219);
            cover.layer.cornerRadius = 3.0f;
            [self insertSubview:cover atIndex:0];
        }];
    } else { // 事件处理，事件继续传递
        [super touchesBegan:touches withEvent:event];
    }
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesMoved:touches withEvent:event];
    
    // 点不在选中的链接上移除选中效果
    if (self.subviews.count > 1) { // 说明有选中的链接，没有选中的链接不作处理
        BOOL isContain = NO;
        for (UIView *childView in self.subviews) {
            if ([childView isKindOfClass:[WBRectView class]]) {
                UITouch *touch = [touches anyObject];
                CGPoint point = [touch locationInView:self];
                if (CGRectContainsPoint(childView.frame, point)) {
                    isContain = YES;
                    break;
                }
            }
        }
        if (!isContain) {
            [self removeCover];
        }
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent:event];
    
    if (self.subviews.count > 1) { // 说明有选中的链接
        for (UIView *childView in self.subviews) {
            if ([childView isKindOfClass:[WBRectView class]]) {
                UITouch *touch = [touches anyObject];
                CGPoint point = [touch locationInView:self];
                if (CGRectContainsPoint(childView.frame, point)) {
                    WBRectView *cover = (WBRectView *)childView;
                    if ([self.delegate respondsToSelector:@selector(textDiyView:didTapLink:)]) {
                        [self.delegate textDiyView:self didTapLink:cover.link];
                    }
                    break;
                }
            }
        }
    }
    
    [self delayRemoveCover];
}

- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesCancelled:touches withEvent:event];
    
    [self delayRemoveCover];
}

- (void)delayRemoveCover
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self removeCover];
    });
}

- (void)removeCover
{
    for (UIView *childView in self.subviews) {
        if ([childView isKindOfClass:[WBRectView class]]) {
            [childView removeFromSuperview];
        }
    }
}

@end


@implementation WBRectView

@end
